package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.User;
import service.Factory.ServiceFactory;

/**
 * Servlet implementation class FindUsersServlet
 */
@WebServlet("/FindUsersServlet")
public class FindUsersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindUsersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String username = request.getParameter("username");
		int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
		int limit = 5;
		
		try {
			List<User> users = ServiceFactory.getUserServiceInstance().findUsers(id == null ? "" : id, username == null ? "" : username, page, limit);
			System.out.println(users.size());
			request.setAttribute("users", users);
			request.setAttribute("_page", page);
			request.setAttribute("hasPrev", page > 1);
			request.setAttribute("hasNext", users.size() == limit);
			request.getRequestDispatcher("/server/login/home.jsp?item=user_list").forward(request, response);
		} catch (NumberFormatException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
